package com.hj.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hj.reggie.common.BusinessException;
import com.hj.reggie.domain.Category;
import com.hj.reggie.domain.Dish;
import com.hj.reggie.domain.Setmeal;
import com.hj.reggie.mapper.CategoryMapper;
import com.hj.reggie.service.CategoryService;
import com.hj.reggie.service.DishService;
import com.hj.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author 37460
 */
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    /**
     * 菜品对象
     */
    private final DishService dishService;

    /**
     * 套餐对象
     */
    private final SetmealService setmealService;

    public CategoryServiceImpl(DishService dishService, SetmealService setmealService) {
        this.dishService = dishService;
        this.setmealService = setmealService;
    }

    /**
     * 根据id删除分类，删除之前需要进行判断
     *
     * @param id 分类id
     */
    @Override
    public void remove(Long id) {
        //查询当前的风雷是否关联了菜品，
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        long dishCount = dishService.count(dishLambdaQueryWrapper);
        if (dishCount > 0) {
            //如果已经关联，抛出一个业务异常
            throw new BusinessException("当前分类下关联了菜品，不能删除");
        }

        //查询当前的分类是否关联了套餐，拖过已经关联，抛出一个业务异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        long setmealCount = setmealService.count(setmealLambdaQueryWrapper);
        if (setmealCount > 0) {
            //如果已经关联，抛出一个业务异常
            throw new BusinessException("当前分类下关联了套餐，不能删除");
        }
        //如果不关联直行删除操作
        //1根据要删除的iDs作为条件  2进行更新IsDeleted字段为1
        super.update(new LambdaUpdateWrapper<Category>().eq(Category::getId, id).set(Category::getIsDeleted, 1));
    }
}
